package com.lhy.hierarchy.ruleEngine.composite.console;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.collect.ImmutableSet;
import com.hauxsoft.core.util.SimpleOption;
import com.hauxsoft.core.util.result.Result;
import com.hauxsoft.core.util.result.Results;
import com.hauxsoft.data.JavaRuleDTO;
import com.hauxsoft.entity.JavaRuleDO;
import com.hauxsoft.service.JavaRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

@RestController("Console.JavaRuleController")
public class JavaRuleController extends BaseConsoleController{
    private static final String API_PATH = "/api/console/java/rules";
    
    @GetMapping(API_PATH)
    public Result<?> queryPage(int pageNo, int pageSize, @RequestParam Map<String, Object> params, 
            @RequestParam(defaultValue="target, group_name, sort asc") String sort) throws ParseException {
        Page<Map<String, Object>> page = service.query(params, pageNo, pageSize, sort);
        return Results.when(page);
    }
    
    @GetMapping(API_PATH + "/{id:[\\d]+}")
    public Result<JavaRuleDTO> get(@PathVariable("id") Long id) {
        return service.getDTO(id);
    }
    
    @PostMapping(API_PATH)
    public Result<?> add(@RequestBody String requestBody) throws Exception{
        return readPojoFromJson(requestBody, JavaRuleDTO.class)
                .run(this::setCreateUserInfo)
                .then(service::insertDTO);
    }
    
    @PutMapping(API_PATH + "/{id:[\\d]+}")
    public Result<?> update(@RequestBody String requestBody) throws Exception{
        return readPojoFromJson(requestBody, JavaRuleDTO.class)
                .run(this::setUpdateUserInfo)
                .then(service::updateDTO);
    }

    @DeleteMapping(API_PATH + "/{id:[\\d]+}")
    public Result<?> delete(@PathVariable("id") Long id) {
    	/*
    	return service.getOne(id)
    			.then(e -> {
    				boolean isError = false;
    				return Results.successOrError(e, isError, "reject reason");
    			})
    			.then(service::delete);
    	*/
        return service.delete(id);
    }
    
    @GetMapping(API_PATH + "/new")
    public Result<?> create() throws Exception{     
        JavaRuleDTO bean = new JavaRuleDTO();
        return Results.when(bean);
    }

    @PostMapping(API_PATH + "/{id:[\\d]+}/enable")
    public Result<?> enable(@PathVariable("id") Long id) {
        /*
    	return service.getOne(id)
    			.then(e -> {
    				boolean isError = false;
    				return Results.successOrError(e, isError, "reject reason");
    			})
    			.then(service::enable);
    	*/
        return service.enable(id);
    }
    
    @PostMapping(API_PATH + "/{id:[\\d]+}/disable")
    public Result<?> disable(@PathVariable("id") Long id) {
        /*
    	return service.getOne(id)
    			.then(e -> {
    				boolean isError = false;
    				return Results.successOrError(e, isError, "reject reason");
    			})
    			.then(service::disable);
    	*/
        return service.disable(id);
    }
    
    @PostMapping(API_PATH + "/{id:[\\d]+}/submit")
    public Result<?> submit(@PathVariable("id") Long id) {
        /*
    	return service.getOne(id)
    			.then(e -> {
    				boolean isError = false;
    				return Results.successOrError(e, isError, "reject reason");
    			})
    			.then(service::submit);
    	*/
        return service.submit(id);
    }
    
    @PostMapping(API_PATH + "/{id:[\\d]+}/withdraw")
    public Result<?> withdraw(@PathVariable("id") Long id) {
        /*
    	return service.getOne(id)
    			.then(e -> {
    				boolean isError = false;
    				return Results.successOrError(e, isError, "reject reason");
    			})
    			.then(service::withdraw);
    	*/
        return service.withdraw(id);
    }

    private static final ImmutableSet<String> ALLOW_TEST_UNIQUE_PROPS = ImmutableSet.of("uniqueProp1", "uniqueProp2");
    @GetMapping(API_PATH + "/unique/{name}")
    public Result<?> isUnique(@PathVariable("name") String name, String value, Long excludeId) {
        return Results.when()
                //判断字段能否检测
                .map(!ALLOW_TEST_UNIQUE_PROPS.contains(name), "request is rejected, invalid unique property name : " + name)
                //调用service进行唯一性检测，唯一则返回success result对象，且content=true；否则content=false
                .map(() -> service.isUnique(name, value, excludeId));
    }
    
    @GetMapping(API_PATH + "/options")
    public Result<?> getOptions(/*String prop1, Integer prop2*/) throws JsonParseException, JsonMappingException, IOException {
        List<SimpleOption> options = service.createJpaQuery()
                /*.whereIfNotNull("prop1", prop1)
                .whereIfNotNull("prop2", prop2)*/
                //.sort("name")
                .list(SimpleOption.class, "new com.hauxsoft.core.util.SimpleOption(id, name)");
        return Results.when(options);
    }
    
    @GetMapping(API_PATH + "/list")
    public Result<?> list(/*String prop1, Integer prop2*/) throws JsonParseException, JsonMappingException, IOException {
        List<JavaRuleDO> beans = service.createJpaQuery()
                /*.whereIfNotNull("prop1", prop1)
                .whereIfNotNull("prop2", prop2)*/
                //.sort("name")
                .list();
        return Results.when(beans);
    }
    
    @Autowired
    private JavaRuleService service;
}